package com.sg.service.biz.framework.nb;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.common.util.RedisUtil;
import com.sg.dto.biz.framework.req.*;
import com.sg.dto.biz.framework.res.*;
import com.wicket.okrcomponent.common.annotations.BanAuto;
import com.wicket.okrframework.common.dto.PublicCacheInfoDto;
import com.wicket.okrframework.common.redis.BaseUserInfoForRealRedis;
import com.wicket.okrframework.common.redis.PublicInfoForRedis;
import com.wicket.okrframework.common.redis.SpaceInfoForRedis;
import com.wicket.okrframework.common.redis.UserIndInfoForRedis;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author ： 手工接入方法
 * @version 1.0
 * @since 2022/5/28 15:32
 */
@Service
public class NbDivineData {
    /**
     * code:collectionRemoveExistingData
     * name:授权权限去除已存在数据
     * desc:undefined
     **/
    @Resource
    private RedisUtil redisClient;

    @BanAuto
    @Trace(operationName = "授权权限去除已存在数据")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public CheckCollectionRemoveExistingDataRespDto checkCollectionRemoveExistingData(
            CheckCollectionRemoveExistingDataReqDto reqDto) {
        CheckCollectionRemoveExistingDataRespDto retData = new CheckCollectionRemoveExistingDataRespDto();
        List<FrameworkSceneRoleDto> filteredPrivacyList = new ArrayList<>(reqDto.getRoleList());
        for (String privacyOne : reqDto.getRoleIdList()) {
            for (FrameworkSceneRoleDto oneRole : reqDto.getRoleList()) {
                if (oneRole.getRoleId().equals(privacyOne)) {
                    filteredPrivacyList.remove(oneRole);
                }
            }
        }
        retData.setRoleList(filteredPrivacyList);
        return retData;
    }

    /**
     * code:getUserRoleListFromRedis
     * name:M-查用户角色缓存Redis列表（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-查用户角色缓存Redis列表（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryUserRoleRedisListRespDto queryUserRoleRedisList(QueryUserRoleRedisListReqDto reqDto) {
        QueryUserRoleRedisListRespDto retData = new QueryUserRoleRedisListRespDto();
        if (redisClient != null && reqDto.getOriginalRoleMemberId() != null) {
            GetUserBasicInfoFromRedisReqDto reqParam = new GetUserBasicInfoFromRedisReqDto();
            reqParam.setOriginalRoleMemberId(reqDto.getOriginalRoleMemberId());
            GetUserBasicInfoFromRedisRespDto userBaseInfo = getUserBasicInfoFromRedis(reqParam);
            List<FrameworkSceneRoleDto> roleList = userBaseInfo.getRoleList();
            retData.setRoleList(roleList);
            return retData;
        }
        return retData;
    }

    /**
     * code:batchClearTokenFromRedis
     * name:M-Redis批量清空用户Token（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-Redis批量清空用户Token（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public BatchClearTokenFromRedisRespDto batchClearTokenFromRedis(BatchClearTokenFromRedisReqDto reqDto) {
        if (reqDto.getBeginMemberList() == null || reqDto.getBeginMemberList().isEmpty()) {
            return new BatchClearTokenFromRedisRespDto();
        }
        for (String member : reqDto.getBeginMemberList()) {
            ClearTokenFromRedisReqDto req = new ClearTokenFromRedisReqDto();
            req.setOriginalRoleMemberId(member);
            clearTokenFromRedis(req);
        }
        return new BatchClearTokenFromRedisRespDto();
    }

    /**
     * code:clearUserInfoFromRedis
     * name:M-Redis清空用户信息（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-Redis清空用户信息（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ClearUserInfoFromRedisRespDto clearUserInfoFromRedis(ClearUserInfoFromRedisReqDto reqDto) {
        if (reqDto.getOriginalRoleMemberId() == null || reqDto.getOriginalRoleMemberId().isEmpty()) {
            return new ClearUserInfoFromRedisRespDto();
        }
        redisClient.delete("登录令牌" + ":" + "userbase-" + reqDto.getOriginalRoleMemberId());
        redisClient.delete("登录令牌" + ":" + "inductionInfo-" + reqDto.getOriginalRoleMemberId());
        return new ClearUserInfoFromRedisRespDto();
    }

    /**
     * code:clearTokenFromRedis
     * name:M-Redis清空用户Token（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-Redis清空用户Token（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ClearTokenFromRedisRespDto clearTokenFromRedis(ClearTokenFromRedisReqDto reqDto) {
        String token = (String) redisClient.get("登录令牌" + ":" + "token-" + reqDto.getOriginalRoleMemberId());
        if (token == null || token.isEmpty()) {
            return new ClearTokenFromRedisRespDto();
        }
        redisClient.delete("登录令牌" + ":" + token);
        redisClient.delete("登录令牌" + ":" + "token-" + reqDto.getOriginalRoleMemberId());
        return new ClearTokenFromRedisRespDto();
    }

    /**
     * code:getUserIrInfoFromRedis
     * name:M-Redis获取用户就职信息（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-Redis获取用户就职信息（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GetUserIrInfoFromRedisRespDto getUserIrInfoFromRedis(GetUserIrInfoFromRedisReqDto reqDto) {
        GetUserIrInfoFromRedisRespDto retData = new GetUserIrInfoFromRedisRespDto();
        String str = (String) redisClient.get("登录令牌" + ":" + "inductionInfo-" + reqDto.getOriginalRoleMemberId());
        if (str == null || str.isEmpty()) {
            return retData;
        }
        UserIndInfoForRedis redisRetData = JSONObject.parseObject(str, UserIndInfoForRedis.class);
        if (redisRetData.getUserIndList() == null) {
            retData.setOrgInductionRecordList(new ArrayList<>());
        } else {
            retData.setOrgInductionRecordList(redisRetData.getUserIndList().stream().map(org -> {
                OrgInductionRecordDto retElm = new OrgInductionRecordDto();
                BeanUtil.copyProperties(org, retElm);
                return retElm;
            }).collect(Collectors.toList()));
        }
        return retData;
    }

    /**
     * code:getUserBasicInfoFromRedis
     * name:M-Redis获取用户基本信息（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-Redis获取用户基本信息（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GetUserBasicInfoFromRedisRespDto getUserBasicInfoFromRedis(GetUserBasicInfoFromRedisReqDto reqDto) {
        GetUserBasicInfoFromRedisRespDto retData = new GetUserBasicInfoFromRedisRespDto();
        String str = (String) redisClient.get("登录令牌" + ":" + "userbase-" + reqDto.getOriginalRoleMemberId());
        if (str == null || str.isEmpty()) {
            return retData;
        }
        BaseUserInfoForRealRedis redisData = JSONObject.parseObject(str, BaseUserInfoForRealRedis.class);
        BeanUtil.copyProperties(redisData, retData, "birthday");
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            if (redisData.getBirthday() != null && !redisData.getBirthday().isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String times = sdf.format(Long.valueOf(redisData.getBirthday()));
                date = ft.parse(times);
                retData.setBirthday(date);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return retData;
    }

    /**
     * code:getSpaceInfoFromRedis
     * name:M-Redis获取空间信息（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-Redis获取空间信息（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GetSpaceInfoFromRedisRespDto getSpaceInfoFromRedis(GetSpaceInfoFromRedisReqDto reqDto) {
        GetSpaceInfoFromRedisRespDto retData = new GetSpaceInfoFromRedisRespDto();
        String str = (String) redisClient.get("登录令牌" + ":" + reqDto.getSpaceId());
        SpaceInfoForRedis redisRetData = JSONObject.parseObject(str, SpaceInfoForRedis.class);
        if (redisRetData != null && redisRetData.getOrgList() == null) {
            retData.setOrgList(new ArrayList<>());
        } else {
            BeanUtil.copyProperties(redisRetData, retData);
            retData.setOrgList(redisRetData.getOrgList().stream().map(org -> {
                OrgDto retElm = new OrgDto();
                BeanUtil.copyProperties(org, retElm);
                return retElm;
            }).collect(Collectors.toList()));
        }
        return retData;
    }

    /**
     * code:collectionRemoveExistingData
     * name:M-查询可用管理部门（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-查询可用管理部门（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryDeptCollectionRemoveExistingDataListRespDto queryDeptCollectionRemoveExistingDataList(
            QueryDeptCollectionRemoveExistingDataListReqDto reqDto) {
        QueryDeptCollectionRemoveExistingDataListRespDto retData = new QueryDeptCollectionRemoveExistingDataListRespDto();
        List<OrgInductionRecordDto> filteredList = new ArrayList<>(reqDto.getOrgInductionRecordList());
        retData.setOrgInductionRecordList(filteredList);
        for (OrgInductionRecordDto oneOrg : reqDto.getOrgInductionRecordList()) {
            for (ManagedDeptListDto oneMange : reqDto.getManagedDeptList()) {
                if (oneOrg.getEntityId().equals(oneMange.getDeptId())) {
                    filteredList.remove(oneOrg);
                }
            }
        }
        return retData;
    }

    /**
     * code:putPublicInfoToRedis
     * name:M-公共信息存储Redis（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-公共信息存储Redis（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public PutPublicInfoToRedisRespDto putPublicInfoToRedis(PutPublicInfoToRedisReqDto reqDto) {
        try {
            PublicInfoForRedis info = BeanUtil.toBean(reqDto, PublicInfoForRedis.class);
            Object jo = JSONArray.toJSON(info);
            redisClient.set("登录令牌" + ":" + "token-" + info.getOriginalRoleMemberId(), reqDto.getToken());
            redisClient.set("登录令牌" + ":" + reqDto.getToken(), jo.toString());
        } catch (Exception ex) {
        }
        return new PutPublicInfoToRedisRespDto();
    }

    /**
     * code:clearUserInfoFromRedis
     * name:M-Redis批量清空用户信息（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-Redis批量清空用户信息（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public BatchClearUserInfoFromRedisRespDto batchClearUserInfoFromRedis(BatchClearUserInfoFromRedisReqDto reqDto) {
        if (reqDto.getBeginMemberList() == null || reqDto.getBeginMemberList().isEmpty()) {
            return new BatchClearUserInfoFromRedisRespDto();
        }
        for (String member : reqDto.getBeginMemberList()) {
            redisClient.delete("登录令牌" + ":" + "userbase-" + member);
            redisClient.delete("登录令牌" + ":" + "inductionInfo-" + member);
        }
        return new BatchClearUserInfoFromRedisRespDto();
    }

    /**
     * code:findLevelCode
     * name:【验证接口】找N级标识
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "【验证接口】找N级标识")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ValidationLookAncestorNodeRespDto validationLookAncestorNode(ValidationLookAncestorNodeReqDto reqDto) {
        String newCode = CommonFunctionHelper.findLevelCode(reqDto.getTestString(), reqDto.getStartNo(), reqDto.getEndNo());
        ValidationLookAncestorNodeRespDto retData = new ValidationLookAncestorNodeRespDto();
        retData.setTestString(newCode);
        return retData;
    }

    /**
     * code:changePublicInfoFromRedis
     * name:M-Redis切换公共信息（后端）（特殊方法）
     * desc:undefined
     **/
    @BanAuto
    @Trace(operationName = "M-Redis切换公共信息（后端）（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ChangePublicInfoFromRedisRespDto changePublicInfoFromRedis(ChangePublicInfoFromRedisReqDto reqDto) {
        String token = (String) redisClient.get("登录令牌" + ":" + "token-" + CommonFunctionHelper.getBaseInfoFromLocal().getSpecOriginalRoleMemberId());
        PublicCacheInfoDto info = CommonFunctionHelper.getPublicInfoFromRedis(redisClient, token);
        if (info == null) {
            return new ChangePublicInfoFromRedisRespDto();
        }
        info.setInductionRecordId(reqDto.getInductionRecordId());
        info.setToken(token);
        Object jo = JSONArray.toJSON(info);
        redisClient.set("登录令牌" + ":" + token, jo.toString());
        return new ChangePublicInfoFromRedisRespDto();
    }

    /**
     * code:getDataCount
     * name:【验证接口】验证计算条数
     * desc:undefined
     **/
    @Trace(operationName = "【验证接口】验证计算条数")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ValidationCalculationMethodRespDto validationCalculationMethod(ValidationCalculationMethodReqDto reqDto) {
        // TODO ruizhe skai dong ; 2022/6/18下午3:50:19
        return new ValidationCalculationMethodRespDto();
    }

    /**
     * code:collectionRemoveExistingData
     * name:M-查询宿主类型可推荐业务场景列表（特殊方法）
     * desc:undefined
     **/
    @Trace(operationName = "M-查询宿主类型可推荐业务场景列表（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryHostTypeCollectionRemoveExistingDataListRespDto queryHostTypeCollectionRemoveExistingDataList(QueryHostTypeCollectionRemoveExistingDataListReqDto reqDto) {
        // TODO ruizhe skai dong ; 2022/6/19上午2:03:38
        return new QueryHostTypeCollectionRemoveExistingDataListRespDto();
    }

    /**
     * code:publicFieldCache
     * name:M1-推送公共字段缓存
     * desc:undefined
     * gen by moon at 8/17/2022, 8:01:29 PM
     **/
    @Trace(operationName = "M1-推送公共字段缓存")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public PutPublicFieldCacheRespDto putPublicFieldCache(PutPublicFieldCacheReqDto reqDto) {
        // TODO ruizhe skai dong ; 8/17/2022, 8:01:29 PM
        return new PutPublicFieldCacheRespDto();
    }

    /**
     * code:collectionRemoveExistingData
     * name:M1-集合去除已存在员工就职记录数据
     * desc:undefined
     * gen by moon at 8/26/2022, 3:03:37 PM
     **/
    @Trace(operationName = "M1-集合去除已存在员工就职记录数据")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddCollectionRemoveExistingDataRespDto addCollectionRemoveExistingData(AddCollectionRemoveExistingDataReqDto reqDto) {
        // TODO ruizhe skai dong ; 8/26/2022, 3:03:37 PM
        return new AddCollectionRemoveExistingDataRespDto();
    }

    /**
     * code:receptionService
     * name:M1-用于接收字段管理场景元素正确
     * desc:undefined
     * gen by moon at 8/26/2022, 10:33:15 PM
     **/
    @Trace(operationName = "M1-用于接收字段管理场景元素正确")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryReceiveFieldDetailRespDto queryReceiveFieldDetail(QueryReceiveFieldDetailReqDto reqDto) {
        // TODO ruizhe skai dong ; 8/26/2022, 10:33:15 PM
        return new QueryReceiveFieldDetailRespDto();
    }

    /**
     * code:collectionRemoveExistingData
     * name:M1查询集合去除已存在的部门数据（特殊方法）
     * desc:undefined
     * gen by moon at 9/12/2022, 12:14:25 AM
     **/
    @Trace(operationName = "M1查询集合去除已存在的部门数据（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryCollectionRemoveDeptExistingDataListRespDto queryCollectionRemoveDeptExistingDataList(QueryCollectionRemoveDeptExistingDataListReqDto reqDto) {
        // TODO ruizhe skai dong ; 9/12/2022, 12:14:25 AM
        return new QueryCollectionRemoveDeptExistingDataListRespDto();
    }
    // 手工接入方法
}
